'''
Created on 2011-5-22

@author: sevear
'''
import web;     
import json;
import errconst;
import model;
import chaosdb;
import time,datetime;

TYPE_RECOMMENDS                 = 1001;
TYPE_RESPONSE_RE                = 1002;
TYPE_ADD_AS_FROM_ID             = 1003;
TYPE_ON_LINE                    = 1004;
TYPE_INVITED_UID_ACTTIVATE      = 1005;
TYPE_TO_USER_LOGIN              = 1006;
TYPE_SITEOPEN_NOTIFY_LISTENER   = 1007;
class Event(object):
    def GET(self):
        i = web.input();
        if(hasattr(i, "uid")):
            uid = int(i.uid);
            if(hasattr(i, "type")):
                print i.type;
                type = int(i.type);
                events = getTypedEvents(type,uid);
                rst = {"type":type,"events":events};
                return json.dumps(rst);
            else:
                if hasattr(i, "time"):
                    timesec= i.time;
                    startDate = datetime.datetime.fromtimestamp(float(timesec));
                else:
                    startDate = datetime.datetime.fromtimestamp(time.time());
                recommends =  model.getRecommendList(uid,startDate.strftime("%Y-%m-%d %H:%M:%S"));
                rst = {"recommends":recommends,"remainReCount":0};
                events = chaosdb.getUnConsumedEvent(uid);
                rst["events"]=json.dumps(getEvtSta(events));
                return json.dumps(rst);
        else:
            errrst = {"errcode":errconst.GET_EVENTS_WITHOUT_UID,"errmsg":"","content":""}
            return json.dumps(errrst);

def getTypedEvents(type,uid):
    events=chaosdb.getTypedEvent(uid, type);
    eventList = [];
    for event in events:
        eventList.append({"id":event.id,
                          "type":event.type,
                          "content":event.content,
                          "uid":event.uid,
                          "time":str(event.time)[0:19]});
    return eventList;

def getEvtSta(events):
    statistics={};
    if(len(events)>0):
        for evItem in events:
            if((evItem.type in statistics) == False):
                statistics[evItem.type] = 1;
            else:
                statistics[evItem.type] = statistics[evItem.type]+1;
    return statistics;

def addEvent(uid,type,content):
    chaosdb.addEvent(type, uid, content);